package cn.lzd.zook;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * Created by lzd on 2018/7/25.
 */
public class Zk3Server {
    private static String connectString = "hdpn:2181,hdpd1:2181,hdpd2:2181";
    private static int sessionTimeout = 2000;

    private ZooKeeper zk = null;
    private String parentNode = "/servers";

    // 创建到 zk 的客户端连接
    public void getConnect() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath()+"。。。。。");
            }
        });
    }

    // 注册服务器
    public void registServer(String hostname) throws Exception {
        String create = zk.create(parentNode + "/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is noline " + create);
    }

    // 业务功能
    public void business(String hostname) throws Exception {
        System.out.println(hostname + " is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {

        // 获取 zk 连接
        Zk3Server server = new Zk3Server();
        server.getConnect();
        // 利用 zk 连接注册服务器信息
        server.registServer("192.11.1.2");

        // 启动业务功能
        server.business("192.11.1.2");
    }
}
